package com.oriental.manage.controller.speciallyUpdate;

import com.oriental.check.commons.util.BeanMapperUtil;
import com.oriental.manage.core.paging.Pagination;
import com.oriental.manage.core.response.ResponseDTO;
import com.oriental.manage.core.utils.SessionUtils;
import com.oriental.manage.model.specially.AreaNumber;
import com.oriental.manage.pojo.specially.BatchMessage;
import com.oriental.manage.pojo.specially.PersonRiskInfo;
import com.oriental.manage.service.specially.BatchMessageService;
import com.oriental.manage.service.specially.PersonRiskInfoService;
import com.oriental.paycenter.commons.utils.DateUtil;
import com.oriental.paycenter.commons.utils.RandomMath;
import com.oriental.riskfront.api.enums.TransCode;
import com.oriental.riskfront.api.model.specially.PersonRiskInfoDto;
import com.oriental.riskfront.api.model.specially.ResponseModel;
import com.oriental.riskfront.api.service.DataDictInterface;
import com.oriental.riskfront.api.service.RiskMsgSearchForUpdateInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by luoxin on 2017/4/20.
 */
@Slf4j
@Controller
@RequestMapping("riskInfo")
public class PersonRiskInfoUpdateController {


@SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private PersonRiskInfoService personRiskInfoService;
    @Autowired
    private DataDictInterface dataDictInterface;
    @Autowired
    private RiskMsgSearchForUpdateInterface riskMsgSearchForUpdateInterface;
    @Autowired
    private BatchMessageService batchMessageService;
    @RequestMapping("personRiskUpdate/init")
    public String init() {

        return "speciallyUpdate/searchPersonRiskMsg";
    }

    @RequestMapping("personRiskUpdate/search")
    @ResponseBody
    public ResponseDTO<Pagination<PersonRiskInfo>> queryPage(Pagination<PersonRiskInfo> pagination, PersonRiskInfo userInfo) {
        ResponseDTO<Pagination<PersonRiskInfo>> responseDTO = new ResponseDTO<Pagination<PersonRiskInfo>>();
        try {
            log.info("个人风险信息变更查询请求参数,userInfo:{}",userInfo);
            PersonRiskInfoDto personRiskInfoDto= BeanMapperUtil.objConvert(userInfo,PersonRiskInfoDto.class);
            ResponseModel<List<PersonRiskInfoDto>> responseModel= riskMsgSearchForUpdateInterface.queryPersonRiskInfoList(personRiskInfoDto);
            log.info("个人风险信息变更查询返回结果,responseModel:{}",responseModel);
            if(!responseModel.isSuccess()){
                responseDTO.setSuccess(false);
                responseDTO.setMsg(responseModel.getErrorMsg());
                return responseDTO;
            }
            List<PersonRiskInfoDto> personRiskInfoDtoList = responseModel.getResult();
            List<PersonRiskInfo> listBody=new ArrayList<>();
            String date1 = "";
            String date2 = "";
            String date3 = "";
            String date4 = "";
            String tmpDate = "";
            String tmpDateb = "";
            String tmpDatee = "";
            List<Map<String, Object>> dataAddress = dataDictInterface.getDataAddress("ADDRESS_Select");
            for(PersonRiskInfoDto personRiskDto:personRiskInfoDtoList){
                //yyyy-MM-DD HH:mm:ss
                date1 = personRiskDto.getRepDate();
                date2 = personRiskDto.getOccurtimeb();
                date3 = personRiskDto.getOccurtimee();
                date4 = personRiskDto.getValidDate();
                tmpDate = DateUtil.parse(date1, DateUtil.settlePattern).getTime() + "";
                personRiskDto.setRepDate(tmpDate);
                if(date2!=null&&!"".equals(date2)) {
                    tmpDateb = DateUtil.parse(date2, DateUtil.shotPattern).getTime() + "";
                 }
                personRiskDto.setOccurtimeb(tmpDateb);
                if(date3!=null&&!"".equals(date3)) {
                    tmpDatee = DateUtil.parse(date3, DateUtil.shotPattern).getTime() + "";
                }
                personRiskDto.setOccurtimee(tmpDatee);

                tmpDate = DateUtil.parse(date4,DateUtil.shotPattern).getTime() + "";
                personRiskDto.setValidDate(tmpDate);
                String areaCode=personRiskDto.getOccurarea();
               // String areaCode="210000,220000,210100";
                PersonRiskInfo info = BeanMapperTestUtil.objConvert(personRiskDto, PersonRiskInfo.class);
                if(areaCode!=null&&!"".equals(areaCode)) {
                    String [] stringArr= areaCode.split(",");
                    List<AreaNumber> basicData = new ArrayList<>();
                    for(int i=0;i<stringArr.length;i++) {
                        AreaNumber areaNumber=new AreaNumber();
                        for (Map<String, Object> map : dataAddress) {
                            String areaCo = (String) map.get("areaCode");
                            String areaCoSub = areaCo.substring(0,2);
                            String areaNa = (String) map.get("areaName");
                            if(areaCo.equals(stringArr[i])){
                                areaNumber.setAreaCode(areaCo);
                                areaNumber.setAreaName(areaNa);
                                areaNumber.setCityName(areaNa);
                                basicData.add(areaNumber);
                            }else {
                                log.info("批量查询数据--------------------------:{}" + stringArr[i]);
                                if (stringArr[i].length()>1) {
                                    if (areaCoSub.equals(stringArr[i].substring(0, 2))) {
                                        areaNumber.setAreaCode(areaCo);
                                        areaNumber.setAreaName(areaNa);
                                        List<Map<String, Object>> citys = (List<Map<String, Object>>) map.get("citys");
                                        for (Map<String, Object> mapCity : citys) {
                                            String cityCo = (String) mapCity.get("cityCode");
                                            String cityNa = (String) mapCity.get("cityName");
                                            if (cityCo.equals(stringArr[i])) {
                                                areaNumber.setCityCode(cityCo);
                                                areaNumber.setCityName(areaNa+cityNa);
                                            }
                                        }
                                        basicData.add(areaNumber);
                                    }
                                }
                            }
                        }
                    }
                    info.setBasicData(basicData);
                }
                info.setRiskId(info.getId());
                listBody.add(info);
            }
            responseDTO.setSuccess(true);
            pagination.setRowCount(listBody.size());
            pagination.setList(listBody);
            log.info("个人风险信息变更查询,pagination:{}",pagination);
            responseDTO.setObject(pagination);
        } catch (Exception e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("personRiskUpdate/toUpdate")
    public String add() {
        return "speciallyUpdate/updatePersonRiskInfo";
    }

    @RequestMapping("personRiskUpdate/toDetail")
    public String queryDetail() {
        return "speciallyUpdate/personRiskInfoUpdateDetail";
    }

    @RequestMapping("personRiskUpdate/update")
    @ResponseBody
    @Transactional
    public ResponseDTO<String> updatePersonRiskInfo(@RequestBody PersonRiskInfo personRiskInfo) {
        ResponseDTO<String> responseDTO = new ResponseDTO<String>();
        BatchMessage batchMessage = new BatchMessage();
        try {//Z2012931000018
            String areaCode=personRiskInfo.getOccurarea();
            if(areaCode.length()>1){
                String code=areaCode.substring(0,1);
                if(",".equals(code)){
                    personRiskInfo.setOccurarea(areaCode.substring(1));
                }
            }else{
                personRiskInfo.setOccurarea("");
            }
            String Id=DateUtil.getCurrent().concat(RandomMath.getNum(5));
            String user = SessionUtils.getUserName();
            personRiskInfo.setRiskId(personRiskInfo.getId());
            personRiskInfo.setId(Id);
           // personRiskInfo.setOrgId("Z2012931000018");
           // personRiskInfo.setCusProperty("01");
          //  personRiskInfo.setRepType("03");
            personRiskInfo.setUpdateType("01");//01补录
            personRiskInfo.setStatus("00");//初始状态
            personRiskInfo.setRepPerson(user);
            batchMessage.setId(DateUtil.getCurrent().concat(RandomMath.getNum(5)));
            batchMessage.setSubmitMsgId(Id);
            batchMessage.setStatus("00");
            batchMessage.setDeleteFlag("0");
            batchMessage.setCount(1);
            batchMessage.setTrnxCode(TransCode.UP0002.getCode());
            batchMessage.setReportDate(new Date());
            batchMessage.setCreateBy(user);
            batchMessage.setDocCode(personRiskInfo.getDocCode());
            batchMessage.setRiskType(personRiskInfo.getRiskType());
            batchMessage.setLevel(personRiskInfo.getLevel());
            log.info("个人风险信息变更,personRiskInfo:{}",personRiskInfo);
            //personRiskInfoService.insert(personRiskInfo, responseDTO);
            //batchMessageService.insertBatchMessage(batchMessage);
            if(personRiskInfo.getRiskId()!=null||!"".equals(personRiskInfo.getRiskId())){
                int number =  personRiskInfoService.queryByRiskId(personRiskInfo.getRiskId());
                if(number<1){
                    personRiskInfoService.insert(personRiskInfo, responseDTO);
                    batchMessageService.insertBatchMessage(batchMessage);
                }else{
                    responseDTO.setSuccess(false);
                    responseDTO.setMsg("该条记录已做处理，请到上报审核页面审批！");
                }
            }
        } catch (Exception e) {
            log.error("新增更新数据失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("personRiskUpdate/delete")
    @ResponseBody
    @Transactional
    public ResponseDTO<String> delete(@RequestBody PersonRiskInfo personRiskInfo) {
        ResponseDTO<String> responseDTO = new ResponseDTO<String>();
        BatchMessage batchMessage = new BatchMessage();
        try {//Z2012931000018
            String areaCode=personRiskInfo.getOccurarea();
            if(areaCode.length()>1){
                String code=areaCode.substring(0,1);
                if(",".equals(code)){
                    personRiskInfo.setOccurarea(areaCode.substring(1));
                }
            }else{
                personRiskInfo.setOccurarea("");
            }
            String Id=DateUtil.getCurrent().concat(RandomMath.getNum(5));
            String user = SessionUtils.getUserName();
            personRiskInfo.setRiskId(personRiskInfo.getId());
            personRiskInfo.setId(Id);
            // personRiskInfo.setOrgId("Z2012931000018");
            // personRiskInfo.setCusProperty("01");
            //  personRiskInfo.setRepType("03");
            personRiskInfo.setUpdateType("02");//02失效
            personRiskInfo.setStatus("00");//初始状态
            personRiskInfo.setRepPerson(user);
            batchMessage.setId(DateUtil.getCurrent().concat(RandomMath.getNum(5)));
            batchMessage.setSubmitMsgId(Id);
            batchMessage.setStatus("00");
            batchMessage.setDeleteFlag("0");
            batchMessage.setCount(1);
            batchMessage.setTrnxCode(TransCode.UP0002_1.getCode());
            batchMessage.setReportDate(new Date());
            batchMessage.setCreateBy(user);
            batchMessage.setDocCode(personRiskInfo.getDocCode());
            batchMessage.setRiskType(personRiskInfo.getRiskType());
            batchMessage.setLevel(personRiskInfo.getLevel());
            log.info("个人风险信息失效,personRiskInfo:{}",personRiskInfo);
            if(personRiskInfo.getRiskId()!=null||!"".equals(personRiskInfo.getRiskId())){
                int number =  personRiskInfoService.queryByRiskId(personRiskInfo.getRiskId());
                if(number<1){
                    personRiskInfoService.insert(personRiskInfo, responseDTO);
                    batchMessageService.insertBatchMessage(batchMessage);
                }else{
                    responseDTO.setSuccess(false);
                    responseDTO.setMsg("该条记录已做处理，请到上报审核页面审批！");
                }
            }
        } catch (Exception e) {
            log.error("新增失效数据失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }


}
